<?php

import("ORG.Util.Function");


class GoodsCatModel extends Model{
		
	// 添加商品分类
	public function addGoodsCategory($datas){
		$GoodsCategoryModel		=	M('Category');
		return  $GoodsCategoryModel->add($datas);
	}
	
	// 插入分类推荐中
	public function insert_cat_recommend($recommend_type, $cat_id){}
	
	// 商品分类列表
	public function getCategoryList(){
		$GoodsCategoryModel		=	M('Category');
		$datas					=	$GoodsCategoryModel->select();
		$datas					=	$this->catsort($datas,0,0);
		$catList				=	array();		
		foreach($datas as $n=>$v){
			$v['cat_name']   	=    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$catList[]			=    $v;
		}		
		return $catList;
	}
	
	// 根据分类id获取分类名
	public function getCatNameById($cat_id){
		$GoodsCategoryModel		=	M('Category');
		$datas					=	$GoodsCategoryModel->field("cat_name")->where("cat_id = '{$cat_id}'")->find();
		return empty($datas['cat_name']) ? '' : $datas['cat_name']; 
	}
	
	// 获取某一分类下有多少子分类
	public function getChildCount($cat_id){
		$GoodsCategoryModel		=	M('Category');
		$datas					=	$GoodsCategoryModel->query("SELECT count(*) count from ybr_category WHERE parent_id = '{$cat_id}'");
		//t($datas);
		return $datas[0]['count'];
	}
	
	// 获取分类下的商品
	public function getGoodsByCatId($cat_id){
		$GoodsModel		=	M('Goods');
		$datas			=	$GoodsModel->field("count(*) count")->join(" left join ybr_category a2 on a2.cat_id = ybr_goods.cat_id  ")
										->where("a2.cat_id = '{$cat_id}'")->select(); 										
		return $datas[0]['count'];
	}
	
	/**
	 * 取得品牌列表
	 * @return array 品牌列表 id => name
	 */
	public static function get_brand_list(){
	    $sql 	= 	'SELECT brand_id, brand_name FROM ybr_brand ORDER BY sort_order';
	    return M()->query($sql);
	}

	/**
	 * 获取商品分类
	 * 
	 */
	public function cat_list(){
		$GoodsCategoryModel		=	M('Category');
		$datas					=	$GoodsCategoryModel->field("cat_id,cat_name,parent_id")->select();
		$datas					=	$this->catsort($datas,0,0);
		$catList				=	array();		
		foreach($datas as $n=>$v){
			$v['cat_name']   	=    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$catList[]			=    $v;
		}
		return $catList;
	}
	
	/**
	 * 排序
	 * Category Sort
	 * @param unknown $arr
	 * @param number $parent_id
	 * @param number $lev
	 * @return multitype:number
	 */
	public function catsort($arr,$parent_id = 0,$lev = 1){
		static $list = array();
		foreach ($arr as $v){
			if($v['parent_id'] == $parent_id){
				$v['lev']  = $lev;
				$list[]    = $v;
				$this->catsort($arr,$v['cat_id'],$lev +1);
			}
		}
		return $list;
	}
	
	
	
	
}